﻿using System;
using AutoBuild.Console.CommandLine;
using AutoBuild.Core;
using AutoBuild.Core.Framework;
using Castle.Windsor;
using log4net.Config;

namespace AutoBuild.Console
{
    public class Program
    {
        //---- Members -----------------------------------------------------
        internal const string DefaultRunner = "NAnt";
        public const string DefaultWatchFolder = ".";
        private readonly CommandLineParser _parser;
        private readonly AutoBuildRunner _autoBuildRunner;
        private readonly IConsole _console;

        //---------------------------------------------------------
        public static int Main(string[] args)
        {
            try
            {
                RunApplication(args);
            }
            catch(InvalidOperationException)
            {
                //errors where printed by log4net
                return 1;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.ToString());
                return 1;
            }
            return 0;
        }

        //---------------------------------------------------------
        private static void RunApplication(string[] args)
        {
            //log4net
            XmlConfigurator.Configure();

            using (var container = new WindsorContainer())
            {
                var configuration = new ConsoleWindsorConfiguration();
                configuration.ConfigureContainer(container);
                container.Resolve<Program>().Run(args);
            }
            
        }

        //---------------------------------------------------------
        public Program(CommandLineParser parser, AutoBuildRunner autoBuildRunner, IConsole console)
        {
            _parser = parser;
            _autoBuildRunner = autoBuildRunner;
            _console = console;
        }

        //---------------------------------------------------------
        private void Run(string[] args)
        {
            var commandLineOptions = _parser.Parse(args);
            if (commandLineOptions.Debug)
            {
                _console.EnableDebugMode();
                _console.Debug("Debug mode enabled!");
            }

            _autoBuildRunner.Start(commandLineOptions);
            System.Console.Read();
        }

    }

   
}